package com.secure.handler;

import cn.hutool.core.codec.Base64Decoder;
import cn.hutool.core.codec.Base64Encoder;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.Sign;
import cn.hutool.crypto.asymmetric.SignAlgorithm;

import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 签名处理器
 */
public class RsaSignatureHandler implements SignatureHandler {

    /**
     * 签名算法
     */
    private final static SignAlgorithm SIGN_ALGORITHM = SignAlgorithm.MD5withRSA;

    /**
     * 签名
     * <p>
     * 按照map里元素顺序组成k1=v1&k2=v2格式字符串进行签名
     *
     * @param plainMap   明文map
     * @param privateKey 私钥
     * @return
     * @throws Exception
     */
    @Override
    public String sign(Map<String, Object> plainMap, String privateKey) {
        String keyValuePairPlainText = map2KeyValuePairText(plainMap);
        Sign sign = SecureUtil.sign(SIGN_ALGORITHM, privateKey, null);
        byte[] signatureBytes = sign.sign(keyValuePairPlainText, StandardCharsets.UTF_8);
        return Base64Encoder.encode(signatureBytes);
    }

    /**
     * 验签
     *
     * @param plainMap  明文字符串,k1=v1&k2=v2格式
     * @param signature 签名
     * @param publicKey 验签公钥
     * @throws Exception
     */
    @Override
    public boolean verify(Map<String, Object> plainMap, String signature, String publicKey) {
        String keyValuePairPlainText = map2KeyValuePairText(plainMap);
        Sign sign = SecureUtil.sign(SIGN_ALGORITHM, null, publicKey);
        return sign.verify(keyValuePairPlainText.getBytes(StandardCharsets.UTF_8), Base64Decoder.decode(signature));
    }
}
